#!/bin/bash

VERSION=${project.version}
DISTRIBUTION_FILE="ourgrid-"$VERSION"-worker.zip"
VM_IMAGE_FILE="linux-vserver-20081216.tar.bz2"

. vserver.functions

# Check if vserver is installed on this machine.
function detect_vserver() {

	if ! isVServerAvailable ; then
		echo
		echo "vserver is not in your path. Please type your PATH to vserver now: [/usr/sbin]"
		read vserver
		if [ -z $vserver ] ; then
			vserver="/usr/sbin"
		fi
		export PATH="$vserver":"$PATH"
	fi
	
	if ! isVServerAvailable ; then
		echo
		echo "You do not have the util-vserver installed in your computer"
		echo "or you  specified a wrong path for vserver."
		echo "You have to install the util-vserver to be able to install OurGrid-VServer."
        	echo "Please install it or contact the system administrator."
        	exit 1
	fi
}

# Check if sudo is installed on this machine.
function detect_sudo() {

	if ! isSudoAvailable ; then
		echo 
		echo "You have to install the sudo package to be able to install vserver."
		echo "Please install it or contact the system administrator."
		echo
		exit 1
	fi
}

function check_user() {

	su $WORKER_USER -c true
	if  [ $? -ne 0 ] ; then
		echo
		echo "User $WORKER_USER does not exist, you have to create it before installation or select another user." 
		exit 1
	fi
}

function detect_kernel_install() {
 
	if ! isVServer_KernelAvailable ; then 
		echo
		echo "===================================================================="
		echo " VServer kernel could not be installed please contact your revendor."
		echo "===================================================================="
		echo
		exit 1
	fi 
}

function config_number_of_workers() {
	
	NUM_WORKERS=0
	echo
	echo "How many workers you want to install? "
	read NUM_WORKERS
}

function config_Install_Place() {

	# Selecting installation place
	if [ -z $INSTALLATION_DIR ]; then
		INSTALLATION_DIR=`pwd`
	fi

	# Verifying if install directory exists
	echo
	echo "Assigned worker installation directory: " $INSTALLATION_DIR
	echo "Verifying if $INSTALLATION_DIR exists..."
	ls $INSTALLATION_DIR > /dev/null 2> /dev/null
	if [ $? -ne 0 ]; then
		echo
		echo "Directory $INSTALLATION_DIR not exists..."
		echo "Creating directory $INSTALLATION_DIR..."
		mkdir $INSTALLATION_DIR 
	fi

	VM_IMAGES_DIR=$INSTALLATION_DIR/vserver_images
	ls $VM_IMAGES_DIR > /dev/null 2> /dev/null

	if [ $? -ne 0 ]; then
		echo
		echo "Directory $VM_IMAGES_DIR not exists..."
		echo "Creating directory $VM_IMAGES_DIR..."
		mkdir $VM_IMAGES_DIR
	fi

	cp $VM_IMAGE_FILE $VM_IMAGES_DIR

	# New reference to base vm image file	
	VM_IMAGE_FILE=$VM_IMAGES_DIR/$VM_IMAGE_FILE

	chown root -R $INSTALLATION_DIR
	
	echo "OK"
}	

# Build the base Virtual Machine
function build_Base_VM() {
	
	echo
	echo "==============================================="
	echo "	Building the base vserver virtual machine ..."
	echo "==============================================="
	
	CURRENT_VM_NAME=$VM_NAME"_"$WORKER_NUM

	vserver $CURRENT_VM_NAME build --context $RANDOM -m template -- -t $VM_IMAGE_FILE -d debian 1>> $LOG_DIR/build_vm_out_$CURRENT_VM_NAME.log 2>>$LOG_DIR/build_vm_error_$CURRENT_VM_NAME.log

	if [ ! $? ] ; then
		echo " An error ocurred in the virtual machine configuration, the installation could not be done."
		exit 1
	fi
}


function create_link_to_vm_image() {
	
	echo
	echo "===================================================="
	echo "	Creating the link to the Virtual Machine Image ..."
	echo "===================================================="

	# Cleaning old vm image
	rm -r /etc/vservers/.defaults/vdirbase/$CURRENT_VM_NAME

	NEW_VM_IMAGE_DIR=$VM_IMAGES_DIR/$CURRENT_VM_NAME
	ls $NEW_VM_IMAGE_DIR > /dev/null 2> /dev/null

	if [ $? -ne 0 ]; then
		echo
		echo "Directory $NEW_VM_IMAGE_DIR not exists..."
		echo "Creating directory $NEW_VM_IMAGE_DIR..."
		mkdir $NEW_VM_IMAGE_DIR
	fi


	ln -s $NEW_VM_IMAGE_DIR /etc/vservers/.defaults/vdirbase/$CURRENT_VM_NAME

	if [ ! $? ] ; then
		echo " An error ocurred on creation of link, the installation could not be done."
		exit 1
	fi

	
}

function extracting_distribution() {

	unzip $DISTRIBUTION_FILE -d $INSTALLATION_DIR

	if [ ! $? ] ; then
		echo " An error ocurred on extraction of the distribution, the installation could not be done."
		exit 1
	fi

	DISTRIBUTION_NAME="worker-"$VERSION

	OLD_DISTRIBUTION_NAME=$DISTRIBUTION_NAME
	DISTRIBUTION_NAME="worker-"$VERSION"_N"$WORKER_NUM	

	mv $INSTALLATION_DIR/$OLD_DISTRIBUTION_NAME $INSTALLATION_DIR/$DISTRIBUTION_NAME

	chmod 744 $INSTALLATION_DIR/$DISTRIBUTION_NAME"/worker"
}

function config_vserver_logDir() {

	LOG_DIR=$INSTALLATION_DIR"/vserver_logs"	
	
	echo
	echo "Verifying if $LOG_DIR exists..."

	ls -la $LOG_DIR &> /dev/null
	if [ $? -ne 0 ]; then
        	echo
		echo "Directory $LOG_DIR not exists..."
		echo "Creating directory $LOG_DIR..."
		mkdir $LOG_DIR
	fi

}


function usage() {

	echo "Usage: install <virtualMachineName> <installationDir> <workerUserName>"
	echo "For OurGrid updates and additional information, see the "
	echo "OurGrid Project home page at http://www.ourgrid.org/ "
}

# Configure the VSERVER_OPTS
function config_OPT_file() {
	
	VSERVER_OPTS=/usr/sbin/VSERVER_OPTS

	ls -la $VSERVER_OPTS &> /dev/null
	if [ ! $? ] ; then
		echo " An error ocurred on configuration of the VSERVER_OPTS. The file [$VSERVER_OPTS] does not exist. The installation could not be done."
		exit 1
	fi

	# Clean the file
	echo "SH=\"/bin/sh\"" > $VSERVER_OPTS

	echo "SUDO=\"/usr/bin/sudo\"" >> $VSERVER_OPTS
	echo "APP_CONTAINER=\"shellApp\"" >> $VSERVER_OPTS
	echo "LOG_DIR=\""$LOG_DIR"\"" >> $VSERVER_OPTS
	echo "WORKER_DIR=\""$INSTALLATION_DIR"\"" >> $VSERVER_OPTS
	echo "WORKER_USER=\""$WORKER_USER"\"" >> $VSERVER_OPTS
	echo "VM_IMAGES_DIR=\""$VM_IMAGES_DIR"\"" >> $VSERVER_OPTS
	echo "VM_IMAGE_FILE=\"$VM_IMAGE_FILE\"" >> $VSERVER_OPTS

}

# Configure the properties of worker
function config_worker_properties() {

	WORKER_PROPERTIES=$INSTALLATION_DIR/$DISTRIBUTION_NAME"/worker.properties"
	
	ls -la $WORKER_PROPERTIES &> /dev/null
	if [ ! $? ] ; then
		echo " An error ocurred on configuration of the worker properties. The file [$WORKER_PROPERTIES] does not exist. The installation could not be done."
		exit 1
	fi

	# Ask the user for some properties of worker
	echo 
	echo "=================================="
	echo "Configuring the Worker Properties"
	echo "=================================="

	answer=
	echo
	echo "What's the user's name of worker on XMPP server? "
	read answer
	echo "commune.xmpp.username="$answer > $WORKER_PROPERTIES

	echo
	echo "What's the name of XMPP server that worker will connect? "
	read answer
	echo "commune.xmpp.servername="$answer >> $WORKER_PROPERTIES

	echo
	echo "What's the user's password of worker on XMPP server? "
	read answer
	echo "commune.xmpp.password="$answer >> $WORKER_PROPERTIES

	echo
	echo "Do you wish enable the idleness detector? [yes/no] "
	read answer
	echo "worker.idlenessdetector="$answer >> $WORKER_PROPERTIES

	answer=`echo $answer | tr '[:upper:]' '[:lower:]'`

	if [ $answer = "yes" -o $answer = "y" ]; then
		echo
		echo "How many seconds for detection of idleness?"
		read answer
		echo "worker.idlenesstime="$answer >> $WORKER_PROPERTIES
	fi
	
	# The property "worker.peer.publickey" must be configured manually
	echo "worker.peer.publickey=" >> $WORKER_PROPERTIES

	echo "worker.playpenroot=/etc/vservers/$CURRENT_VM_NAME/vdir/local/playpen" >> $WORKER_PROPERTIES

	# Configure the worker's properties to use vserver executor
	echo "worker.executor=VSERVER" >> $WORKER_PROPERTIES
	echo "worker.VM_NAME="$CURRENT_VM_NAME >> $WORKER_PROPERTIES
	echo "worker.PREPARE_ALLOCATION_COMMAND=/usr/sbin/vserver_prepare_allocation" >> $WORKER_PROPERTIES
	echo "worker.COPY_FILES_COMMAND=/usr/sbin/vserver_copy_files" >> $WORKER_PROPERTIES
	echo "worker.REPLACE_VM_IMAGE_COMMAND=/usr/sbin/vserver_replace_vm_image" >> $WORKER_PROPERTIES
	echo "worker.START_VM_COMMAND=/usr/sbin/vserver_initvm" >> $WORKER_PROPERTIES
	echo "worker.STOP_VM_COMMAND=/usr/sbin/vserver_stopvm" >> $WORKER_PROPERTIES
	echo "worker.STOP_PREPARING_ALLOCATION_COMMAND=/usr/sbin/vserver_stop_preparing_allocation" >> $WORKER_PROPERTIES
	echo "worker.KILL_TAR_PROC_COMMAND=/usr/sbin/vserver_kill_tar_proc" >> $WORKER_PROPERTIES
	echo "worker.EXEC_COMMAND=/usr/sbin/vserver_exec" >> $WORKER_PROPERTIES
	echo "worker.STATUS_VM_COMMAND=/usr/sbin/vserver_status" >> $WORKER_PROPERTIES
	echo "worker.VM_PLAYPEN=/local/playpen" >> $WORKER_PROPERTIES
	echo "worker.VM_STORAGE=/local/storage" >> $WORKER_PROPERTIES


}

# main() - Checking for dependencies.

# Assign the variables
nargs=$#

if [ $nargs -eq 3 ]; then
	VM_NAME=$1
	INSTALLATION_DIR=$2
	WORKER_USER=$3

else 
	usage
	exit 1
fi


echo
echo "================================="
echo "   Ready to begin installation   "
echo "================================="
echo
echo "==========================="
echo "   Checking dependencies   "
echo "==========================="
echo

echo -n "Checking for Sudo ... "
detect_sudo
echo "OK"
echo

echo -n "Checking for vserver ... "
detect_vserver
echo "OK"
echo

echo -n "Checking for vserver kernel ... "
detect_kernel_install
echo "OK"
echo

echo
echo "======================"
echo "   Configuring VServer"
echo "======================"
echo

echo "Assigned vserver user name: " $WORKER_USER
check_user

# main() - Installing Worker
echo
echo "======================="
echo "   Installing Worker   "
echo "======================="
echo
echo "Installing the OurGrid Worker"

config_number_of_workers

config_Install_Place
config_vserver_logDir

for WORKER_NUM in $(seq 1 $NUM_WORKERS)
do

extracting_distribution

build_Base_VM
create_link_to_vm_image

config_worker_properties

done

config_OPT_file


# Changing the owner of worker dir
chown $WORKER_USER -R $INSTALLATION_DIR
# Setting the worker binary as executable


echo
echo "====================================="
echo "   You're done. Worker is installed."
echo "====================================="
echo 
